//
//  YQArticleDetailHeader.m
//  iyuanqi
//
//  Created by zhaoliang chen on 2018/10/31.
//  Copyright © 2018 czl. All rights reserved.
//

#import "YQArticleDetailHeader.h"
#import <WebKit/WebKit.h>

@interface YQArticleDetailHeader ()
<WKUIDelegate,WKNavigationDelegate>

@property(nonatomic,strong)UILabel* labelSubject;
@property(nonatomic,strong)UILabel* labelTime;
@property(nonatomic,strong)UIImageView* imHeader;
@property(nonatomic,strong)UILabel* labelName;
@property(nonatomic,strong)WKWebView* webDetail;

@end

@implementation YQArticleDetailHeader

- (instancetype)initWithFrame:(CGRect)frame {
    if (self == [super initWithFrame:frame]) {
        self.clipsToBounds = YES;
        
        [self addSubview:self.labelSubject];
        [self.labelSubject mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.mas_equalTo(10);
            make.right.mas_equalTo(-10);
        }];
        
        [self addSubview:self.labelTime];
        [self.labelTime mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.labelSubject);
            make.top.mas_equalTo(self.labelSubject.mas_bottom).offset(5);
        }];
        
        [self addSubview:self.imHeader];
        [self.imHeader mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.labelSubject);
            make.top.mas_equalTo(self.labelTime.mas_bottom).offset(10);
            make.size.mas_equalTo(40);
        }];
        
        [self addSubview:self.labelName];
        [self.labelName mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.imHeader.mas_right).offset(10);
            make.centerY.mas_equalTo(self.imHeader);
        }];
        
        [self addSubview:self.webDetail];
        self.webDetail.scrollView.scrollEnabled = NO;
        [self.webDetail mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.imHeader.mas_bottom).offset(10);
            make.left.right.mas_equalTo(self);
            make.height.mas_equalTo(10).priorityLow();
            make.bottom.mas_equalTo(-10);
        }];
    }
    return self;
}

- (void)setArticleObject:(YQArticleObject *)articleObject {
    _articleObject = articleObject;
    
    self.labelSubject.text = articleObject.subject;
    self.labelTime.text = compareCurrentTime(getIntervalTimeByInterval(articleObject.dateline));
    [self.imHeader sd_setImageWithURL:[NSURL URLWithString:articleObject.head_img] placeholderImage:[UIImage imageNamed:@"loadimage"]];
    self.labelName.text = articleObject.author;
    [self.webDetail loadHTMLString:[self operateHtml:articleObject.message] baseURL:nil];
}

// 页面加载完成之后调用 此方法会调用多次
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    __block CGFloat webViewHeight;

    //获取内容实际高度（像素）@"document.getElementById(\"content\").offsetHeight;"
    WeakSelf;
    [webView evaluateJavaScript:@"document.body.scrollHeight" completionHandler:^(id _Nullable result,NSError * _Nullable error) {
        // 此处js字符串采用scrollHeight而不是offsetHeight是因为后者并获取不到高度，看参考资料说是对于加载html字符串的情况下使用后者可以(@"document.getElementById(\"content\").offsetHeight;")，但如果是和我一样直接加载原站内容使用前者更合适
        //获取页面高度，并重置webview的frame
        webViewHeight = [result doubleValue];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (webViewHeight != weakSelf.webDetail.height) {
                //高度重置
                //weakSelf.webDetail.height = webViewHeight*2;
                //weakSelf.webDetail.scrollView.height = webViewHeight*2;
                [weakSelf.webDetail mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.height.mas_equalTo(webViewHeight+20).priorityHigh();
                }];
                [self layoutIfNeeded];
            }
        });
        
        if (weakSelf.onLoadFinish) {
            weakSelf.onLoadFinish(webViewHeight);
        }
    }];
}

- (NSString*)operateHtml:(NSString*)contentStr {
    NSString *result = [NSString stringWithFormat:@"<%@ %@",@"img",@"style='display: block; max-width: 100%;'"];
    contentStr = [contentStr stringByReplacingOccurrencesOfString:@"<img" withString:result];
    NSString *htmlStr = [NSString stringWithFormat:@"<html><head><meta http-equiv=\'Content-Type\' content=\'text/html; charset=utf-8\'/><meta content=\'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;\' name=\'viewport\' /><meta name=\'apple-mobile-web-app-capable\' content=\'yes\'><meta name=\'apple-mobile-web-app-status-bar-style\' content=\'black\'><link rel=\'stylesheet\' type=\'text/css\' /><style type=\'text/css\'> .color{color:#576b95;}</style></head><body><div id=\'content\'>%@</div>", contentStr];
    return htmlStr;
}

- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"%@",error.localizedDescription);
}

- (UILabel *)labelSubject{
    if(!_labelSubject){
        _labelSubject = ({
            UILabel * object = [[UILabel alloc]init];
            object.numberOfLines = 0;
            object;
       });
    }
    return _labelSubject;
}

- (UILabel *)labelTime{
    if(!_labelTime){
        _labelTime = ({
            UILabel * object = [[UILabel alloc]init];
            object.font = DefaultFont;
            object;
       });
    }
    return _labelTime;
}

- (UIImageView *)imHeader{
    if(!_imHeader){
        _imHeader = ({
            UIImageView * object = [[UIImageView alloc]init];
            object.layer.masksToBounds = YES;
            object.layer.cornerRadius = 20;
            object;
       });
    }
    return _imHeader;
}

- (UILabel *)labelName{
    if(!_labelName){
        _labelName = ({
            UILabel * object = [[UILabel alloc]init];
            object.font = DefaultFont;
            object;
       });
    }
    return _labelName;
}

- (WKWebView *)webDetail{
    if(!_webDetail){
        _webDetail = ({
            WKWebView * object = [[WKWebView alloc]init];
            object.UIDelegate = self;
            object.navigationDelegate = self;
            object;
       });
    }
    return _webDetail;
}


@end
